import axios from 'axios';
import {Notification} from 'element-ui';
import router from "@/router/"
//设置baseURL
axios.defaults.baseURL = 'http://localhost:3003';
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
	
	//提取token
	let token = sessionStorage.token;
	//添加至headers
	config.headers.Authorization = `Bearer ${token}`;
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
// 添加响应拦截器
axios.interceptors.response.use(function({ data, status }) {
	//在这里你可以判断后台返回数据携带的请求码
	if (status === 200) {
		
		return data;
	}
}, function({response}){
	let{status,data} = response;
	switch(status){
		case 401:
		//错误提示框
		Notification.error({
			title:`错误:${status}`,
			message:'token过期,请重新登录账户',
			duration:0,
		});
		let {fullPath} = router.history.current;
		//强制跳转
		router.replace({path:'/login',query:{redirect:fullPath}});
		break;
		case 404:
		//错误提示框
		Notification.error({
			title:`错误: ${status}`,
			message:'api接口错误,请重新检查!',
			duration:0,
		});
		break;
		case 500:
		//错误提示框
		Notification.error({
			title:`错误: ${status}`,
			message:'后台接口错误,请联系后台',
			duration:0,
		});
		break;
		default:
		break;
	}
});
